#include "soduku.h"
#include "fastcgi.h"
#include "../../base/Utils.h"
#include "../../logging/Logging.h"
#include "../EventLoop.h"
#include "../TcpServer.h"

using namespace yhaida;

const std::string kPath = "/sudoku/";

void onRequest(const TcpConnectionPtr &conn,
               FastCgiCodec::ParamMap &params,
               Buffer *in)//&_stdin
{
    std::string uri = params["REQUEST_URI"];
    LOG_INFO << conn->name() << ": " << uri;

    for(FastCgiCodec::ParamMap::const_iterator it = params.begin();it!=params.end();++it)
    {
        LOG_DEBUG << it->first << " = " << it->second;
    } 
    if(in->readableBytes()>0)
    {
        LOG_DEBUG << "stdin " << in->retrieveAllAsString();
    }

    Buffer response;
    response.append("Context-Type: text/plain\r\n\r\n");
    if(uri.size()== kPath.size() + kCells && uri.find(kPath) == 0 )
    {
        response.append(solveSudoku(uri.substr(kPath.size())));
    }
    else
    {
        response.append("bad request");
    }
    FastCgiCodec::respond(&response);
    conn->send(&response);
}
void onConnection(const TcpConnectionPtr &conn)
{
    if (conn->connected())
    {
        typedef std::shared_ptr<FastCgiCodec> CodecPtr;
        CodecPtr codec(new FastCgiCodec(onRequest));
        conn->setContext(codec);
        conn->setMessageCallback(
            std::bind(&FastCgiCodec::onMessage,codec,_1,_2,_3));
        conn->setTcpNoDelay(true);
    }
}

int main(int argc, char *argv[])
{
    // Logging::setLogLevel(Logging::TRACE);
    int port = 19981;
    int threads = 0;
    if (argc > 1)
        port = atoi(argv[1]);
    if (argc > 2)
        threads = atoi(argv[2]);

    InetAddress addr(static_cast<uint16_t>(port));
    LOG_INFO << "Sudoku FastCGI listens on " << addr.toHostPort()
             << " threads " << threads;
    EventLoop loop;
    TcpServer server(&loop, addr);
    server.setConnectionCallback(onConnection);
    server.setThreadNum(threads);
    server.start();
    loop.loop();
}
//100000000020000000003000000000400000000050000000006000000000700000000080000000009
